import { checkIsWx } from './userAgent';

// https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html#3
const WECHAT_JS_SDK_URL = 'https://res.wx.qq.com/open/js/jweixin-1.6.0.js';
const WECHAT_JS_SDK_URL_2 = 'https://res2.wx.qq.com/open/js/jweixin-1.6.0.js';

async function loadScript(url, timeout = 3000) {
  return new Promise((resolve, reject) => {
    let script = document.createElement('script');
    script.type = 'text/javascript';
    script.onload = () => {
      resolve();
    };
    script.onerror = (e) => {
      console.warn(e);
      reject(new Error('LoadScriptFailed'));
    };
    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);

    setTimeout(() => {
      reject(new Error(`Timeout, url: ${url}`));
    }, timeout);
  });
}

async function loadWechatSdk() {
  if (typeof window.wx !== 'undefined') {
    return;
  }

  return loadScript(WECHAT_JS_SDK_URL).catch((e) => {
    console.warn(e);
    return loadScript(WECHAT_JS_SDK_URL_2);
  });
}

async function loadJSSdk() {
  const platform = checkIsWx();
  if (platform) {
    await loadWechatSdk();
  }

  return platform;
}

export { loadWechatSdk, loadJSSdk };
